using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyHomeworkWebAPi.Models;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;
using MyHomeworkWebAPi.Models.response;
using MyHomeworkWebAPi.Services;

namespace MyHomeworkWebAPi.Controllers
{
    /// <summary>
    /// 用户管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IUserServices _userServices;
        private readonly ILogger<UsersController> _logger;

        /// <summary>
        /// 构造函数，注入用户服务
        /// </summary>
        /// <param name="userServices">用户服务接口</param>
        /// <param name="logger">日志服务</param>
        public UsersController(IUserServices userServices, ILogger<UsersController> logger)
        {
            _userServices = userServices;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns>用户列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var users = await _userServices.GetAllAsync();
            return Ok(ApiResponse<List<Models.ef.User>>.SuccessResponse(users));
        }

        /// <summary>
        /// 根据ID获取用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户信息</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(Guid id)
        {
            var user = await _userServices.GetByIdAsync(id);
            if (user == null)
            {
                return NotFound(ApiResponse<Models.ef.User>.ErrorResponse("用户不存在", 404));
            }
            return Ok(ApiResponse<Models.ef.User>.SuccessResponse(user));
        }

        /// <summary>
        /// 检查学号是否已被注册
        /// </summary>
        /// <param name="studentId">学号</param>
        /// <returns>true表示已存在，false表示不存在</returns>
        [HttpGet("check/studentId/{studentId}")]
        public async Task<IActionResult> CheckStudentId(string studentId)
        {
            var exists = await _userServices.IsStudentIdExistsAsync(studentId);
            return Ok(ApiResponse<bool>.SuccessResponse(exists));
        }

        /// <summary>
        /// 检查用户名是否已被使用
        /// </summary>
        /// <param name="nickname">用户名</param>
        /// <returns>true表示已存在，false表示不存在</returns>
        [HttpGet("check/nickname/{nickname}")]
        public async Task<IActionResult> CheckNickname(string nickname)
        {
            var exists = await _userServices.IsNicknameExistsAsync(nickname);
            return Ok(ApiResponse<bool>.SuccessResponse(exists));
        }

        /// <summary>
        /// 检查手机号是否已被注册
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <returns>true表示已存在，false表示不存在</returns>
        [HttpGet("check/phone/{phone}")]
        public async Task<IActionResult> CheckPhone(string phone)
        {
            var exists = await _userServices.IsPhoneExistsAsync(phone);
            return Ok(ApiResponse<bool>.SuccessResponse(exists));
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model">登录信息</param>
        /// <returns>JWT令牌</returns>
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginModel model)
        {
            try
            {
                var token = await _userServices.LoginAsync(model);
                _logger.LogInformation($"User {model.StudentId} logged in successfully");
                return Ok(ApiResponse<string>.SuccessResponse(token, "登录成功"));
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Login failed for user {model.StudentId}: {ex.Message}");
                return BadRequest(ApiResponse<string>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="request">注册请求信息，包含学号、用户名、密码和手机号</param>
        /// <returns>注册成功返回用户信息，失败返回错误信息</returns>
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] UserRegisterRequest request)
        {
            try
            {
                var user = await _userServices.RegisterAsync(request);
                _logger.LogInformation($"User {request.Nickname} registered successfully");
                return Ok(ApiResponse<Models.ef.User>.SuccessResponse(user, "注册成功"));
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Registration failed for user {request.Nickname}: {ex.Message}");
                return BadRequest(ApiResponse<Models.ef.User>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 测试认证
        /// </summary>
        /// <returns>认证状态</returns>
        [Authorize]
        [HttpGet("test-auth")]
        public IActionResult TestAuth()
        {
            return Ok(ApiResponse<string>.SuccessResponse("认证成功"));
        }

        /// <summary>
        /// 更新用户昵称
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="nickname">新昵称</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPut("{id}/nickname")]
        public async Task<IActionResult> UpdateNickname(Guid id, [FromQuery] string nickname)
        {
            try
            {
                var user = await _userServices.UpdateNicknameAsync(id, nickname);
                return Ok(ApiResponse<Models.ef.User>.SuccessResponse(user, "昵称更新成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<Models.ef.User>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 更新用户手机号
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="phone">新手机号</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPut("{id}/phone")]
        public async Task<IActionResult> UpdatePhone(Guid id, [FromQuery] string phone)
        {
            try
            {
                var user = await _userServices.UpdatePhoneAsync(id, phone);
                return Ok(ApiResponse<Models.ef.User>.SuccessResponse(user, "手机号更新成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<Models.ef.User>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 更新用户密码
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPut("{id}/password")]
        public async Task<IActionResult> UpdatePassword(Guid id, [FromQuery] string oldPassword, [FromQuery] string newPassword)
        {
            try
            {
                var user = await _userServices.UpdatePasswordAsync(id, oldPassword, newPassword);
                return Ok(ApiResponse<Models.ef.User>.SuccessResponse(user, "密码更新成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<Models.ef.User>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="avatar">新头像文件名</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPut("{id}/avatar")]
        public async Task<IActionResult> UpdateAvatar(Guid id, [FromQuery] string avatar)
        {
            try
            {
                var user = await _userServices.UpdateAvatarAsync(id, avatar);
                return Ok(ApiResponse<Models.ef.User>.SuccessResponse(user, "头像更新成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<Models.ef.User>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(Guid id)
        {
            var result = await _userServices.DeleteAsync(id);
            if (!result)
            {
                return NotFound(ApiResponse<bool>.ErrorResponse("用户不存在", 404));
            }
            return Ok(ApiResponse<bool>.SuccessResponse(true, "用户删除成功"));
        }
    }
}
